package com.yzc.rabbit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yzc.constants.MqConstants;
import com.yzc.mapper.OrderStatusLogMapper;
import com.yzc.mapper.TicketAttractionOrderMapper;
import com.yzc.message.RollbackInventoryMessage;
import com.yzc.model.entity.ticket_order.OrderStatusLog;
import com.yzc.model.vo.ticket_order.v_AttractionOrderVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
@RequiredArgsConstructor
public class InventoryService {

    private final TicketAttractionOrderMapper attractionOrderMapper;
    private final RabbitTemplate rabbitTemplate;
    private final OrderStatusLogMapper logMapper;

    /**
     * 回滚库存
     *
     * @param orderId 订单ID
     */
    @Transactional
    public void rollbackInventory(Long orderId) {
        // 查询订单信息
        v_AttractionOrderVo attractionOrderVo = attractionOrderMapper.selectUserInfoByorderId(orderId);
        log.error(String.valueOf(attractionOrderVo));

        if (attractionOrderVo == null) {
            log.warn("未找到订单信息，订单ID: {}", orderId);
            return;
        }

        // 幂等性检查：检查库存是否已经回滚
        if (isInventoryRolledBack(orderId)) {
            log.info("库存已回滚，无需重复操作，订单ID: {}", orderId);
            return;
        }

        // 发送回滚消息
        RollbackInventoryMessage message = new RollbackInventoryMessage();
        message.setOrderId(orderId);
        message.setProductId(attractionOrderVo.getAttractionId());
        message.setQuantity(attractionOrderVo.getTicketCount());


        try {
            // 发送消息到队列
            rabbitTemplate.convertAndSend(
                    MqConstants.ROLLBACK_INVENTORY_EXCHANGE, // 交换机名称
                    "rollback.inventory",                   // 路由键
                    message                                 // 消息内容
            );
            log.info(" [x] 成功发送回滚库存消息，订单ID: {}", orderId);

            // 记录回滚日志
            OrderStatusLog orderStatusLog = new OrderStatusLog();
            orderStatusLog.setOrderId(orderId);
            orderStatusLog.setStatus(attractionOrderVo.getOrderStatus());
            orderStatusLog.setOperator("system");
            orderStatusLog.setRemark("库存回滚");
            orderStatusLog.setCreateTime(new Date());
            logMapper.insert(orderStatusLog);
        } catch (Exception e) {
            log.error("发送回滚库存消息失败，订单ID: {}", orderId, e);
            throw new RuntimeException("发送回滚库存消息失败", e);
        }
    }

    //  检查库存是否已经回滚,日志中是否记录了 "库存回滚"
    boolean isInventoryRolledBack(Long orderId) {
        LambdaQueryWrapper<OrderStatusLog> logQueryWrapper = new LambdaQueryWrapper<>();
        logQueryWrapper.eq(OrderStatusLog::getOrderId, orderId)
                .eq(OrderStatusLog::getRemark, "库存回滚");
        return logMapper.selectCount(logQueryWrapper) > 0;
    }
}